package com.example.provider.qiniuyunDemo;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.persistent.FileRecorder;
import com.qiniu.util.Auth;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Paths;

/**
 * All rights Reserved, Designed By www.maihaoche.com
 *
 * @Package com.example.provider.qiniuyunDemo
 * @author: 红雪（hongxue@maihaoche.com）
 * @date: 2019/1/25 4:35 PM
 * @Copyright: 2017-2020 www.maihaoche.com Inc. All rights reserved.
 * 注意：本内容仅限于卖好车内部传阅，禁止外泄以及用于其他的商业项目
 */
public class OpenDemo {

    private static final String accessKey = "fLEC-LbT3c--z6TfdwtXPFuT2SJ6H4q1GMk8FrHK";
    private static final String secretKey = "1RnMit0n19dCsC3arcio0qlgbqh_AFZhJO8l1M1I";
    private static final String openBucket = "hongxueopen";
    private static final String uploadPath = "/Users/durui/Pictures/";
    private static final String domain = "plvou2uto.bkt.clouddn.com";

    //返回文件下载的链接
    public static void download() throws UnsupportedEncodingException {
        String fileName = "hongxue.jpg";
        String domainOfBucket = domain;
        String encodedFileName = URLEncoder.encode(fileName, "utf-8");
        String finalUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        System.out.println(finalUrl);
    }


    public static void main(String[] args) {
        simpleUpload();
        //byteArrayUpload();
        //resumeUpload();

        /*try {
            download();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/



    }

    //普通文件上传
    public static void simpleUpload(){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);


        //如果是Windows情况下，格式是 D:\\qiniu\\test.png
        String localFilePath = uploadPath+"test.jpg";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = "hongxue/hongxue.jpg";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(openBucket);
        System.out.println(upToken);
        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
    }

    //字节数组上传
    public static void byteArrayUpload(){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        try {
            byte[] uploadBytes = "hello hongxue".getBytes("utf-8");
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(openBucket);
            try {
                Response response = uploadManager.put(uploadBytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (UnsupportedEncodingException ex) {
            //ignore
        }
    }

    //断点续传
    public static void resumeUpload(){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        String localFilePath = uploadPath+"fileBig.rar";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = "hongxue.rar";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(openBucket);
        String localTempDir = Paths.get(uploadPath, openBucket).toString();
        try {
            //设置断点续传文件进度保存目录
            FileRecorder fileRecorder = new FileRecorder(localTempDir);
            UploadManager uploadManager = new UploadManager(cfg, fileRecorder);
            try {
                Response response = uploadManager.put(localFilePath, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
